<template>
    <el-dialog v-model="showDialog" title="冲突发票处理" :close-on-click-modal="false" width="1100">

        <el-date-picker v-if="showDate" class="mg-b-20" value-format="YYYY-MM" v-model="selectMonth" type="month"
                        placeholder="请选择" @change="handleDateChange"/>

        <div class="flex">
            <div class="left-box flex-1">
                <div class="flex">
                    <div class="left limitHeight">
                        <template v-if="ticketList.length">
                            <div v-for="(i, index) in ticketList" :key="index" class="item" :title="i.companyName"
                                 :class="{ 'active': curItem.id === i.id }" @click="handleClick(i)">
                                <div class="flex flex-jc-sb">
                                    <div>
                                        <span>产品类型：</span>
                                        <span>{{ filterName(i.type) }}</span>
                                    </div>
                                    <div>
                                        <span>发票月份：</span>
                                        <span>{{ i.month }}</span>
                                    </div>
                                </div>
                                <div class="flex flex-jc-sb">
                                    <div class="companyName">{{ i.companyName }}</div>
                                    <div class="fc-success" @click.stop="handlePreview(i)">预览</div>
                                </div>
                            </div>
                        </template>
                        <template v-else>
                            <div class="fc-gray text-center">
                                暂无数据
                            </div>
                        </template>
                    </div>
                    <div class="center limitHeight">
                        <div class="flex items-center justify-between">
                            <div>
                                <el-checkbox
                                    v-model="checkAll"
                                    :indeterminate="isIndeterminate"
                                    @change="handleCheckAllChange"
                                >
                                    全选
                                </el-checkbox>
                            </div>
                            <div>合计：{{ totalMoney }}元</div>
                        </div>
                        <div v-for="k in ticketDetailList" class="check-box">
                            <el-checkbox v-model="k.checked" :disabled="k.disabled" @change="handleChange($event, k)">
                                <span :class="{ 'disabled': k.disabled }">{{ k.invoiceName }}（{{ k.amount }}元）</span>
                            </el-checkbox>
                        </div>
                        <!--                        <div class="calc-box">-->
                        <!--                            合计：{{ totalMoney }}元-->
                        <!--                        </div>-->
                    </div>
                </div>
            </div>
            <div class="right flex-1 limitHeight">
                <div class="mg-b-10 flex items-center justify-between">
                    <div>
                        已选择:{{ selectList.length }}个
                    </div>
                    <el-button v-if="selectList.length!==0" type="danger" text @click="onClearAll">全部清除</el-button>
                </div>
                <div v-for="(i, index) in selectList"
                     class="select-item flex items-center w-full box-border justify-between gap-10px" :key="index">
                    <div class="flex-auto">
                        <div class="flex flex-jc-sb">
                            <div>
                                <span>产品类型：</span>
                                <span>{{ filterName(i.type) }}</span>
                            </div>
                            <div>
                                <span>发票月份：</span>
                                <span>{{ i.ticketMonth }}</span>
                            </div>
                            <div>
                                <span>应用月份：</span>
                                <span>{{ i.month }}</span>
                            </div>
                        </div>
                        <div class="flex flex-jc-sb">
                            <div class="companyName">{{ i.companyName }}</div>
                            <div class="fc-success" @click.stop="handlePreview(i)">预览</div>
                        </div>
                    </div>
                    <div>
                        <el-button icon="Delete" circle type="danger" @click="onClearItem(i,index)"></el-button>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleConfirm">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <previewDialog v-model:show="showPreview" v-model:url="previewUrl"/>
</template>
<script setup>
import {ref, onMounted, watch} from 'vue'
import {queryNeedUploadList, syncInvoice} from '@/api/approval/upload.ts'
import previewDialog from '@/components/previewDialog/index.vue'
import Decimal from 'decimal.js'
import dayjs from 'dayjs'
import {Delete} from "@element-plus/icons-vue";

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    list: {
        type: Array,
        default() {
            return []
        }
    },
    showDate: {
        type: Boolean,
        default: false,
    },
    month: {
        type: String,
        default: ''
    }
})

const curItem = ref('')

const ticketList = ref([])
const ticketDetailList = ref([])

const showPreview = ref(false)
const previewUrl = ref('')

const totalMoney = ref(0)

const selectMonth = ref('')

const emits = defineEmits(['update:show', 'success', 'update:month'])

const showDialog = ref(false)

const checkAll = ref(false)
const isIndeterminate = ref(false)
const handleCheckAllChange = (val) => {
    if (val) {
        checkAll.value = true
        isIndeterminate.value = false
        totalMoney.value = 0
        ticketDetailList.value.forEach(i => {
            if (!i.disabled) {
                i.checked = true
                i.uploadId = curItem.value.id
                i.invoiceUrl = curItem.value.invoiceUrl
                i.disableId = curItem.value.id
                i.type = curItem.value.type
                i.ticketMonth = curItem.value.month
                selectList.value.push(i)
                totalMoney.value = Decimal.add(totalMoney.value, i.amount)
            }
            // totalMoney.value += i.amount
        })
    } else {
        checkAll.value = false
        // totalMoney.value = 0
        ticketDetailList.value.forEach(item => {
            const index = selectList.value.findIndex(i => i.id === item.id)
            if (index !== -1) {
                selectList.value.splice(index, 1)
                totalMoney.value = Decimal.sub(totalMoney.value, item.amount)
            }
            item.checked = false
            item.disabled = false
            // selectList.value = []
        })
    }
    const map = new Map();
    selectList.value.forEach(item => {
        if (!map.has(item.id)) {
            map.set(item.id, item);
        }
    });
    selectList.value = Array.from(map.values());
}
const onClearItem = (item, index) => {
    selectList.value.splice(index, 1)
    totalMoney.value -= item.amount
    handleClick(curItem.value)
}
const onClearAll = () => {
    ticketDetailList.value.forEach(i => {
        i.checked = false
    })
    totalMoney.value = 0
    checkAll.value = false
    isIndeterminate.value = false
    selectList.value = []
}
const handleClick = (item) => {
    curItem.value = item
    const params = {
        companyName: item.companyName,
        voiceType: item.type
    }
    queryNeedUploadList(params).then(res => {
        ticketDetailList.value = res
        ticketDetailList.value.forEach(i => {
            i.checked = false
            i.disabled = false
            i.disableId = curItem.value.id
        })
        console.log(selectList.value, 'selectList')
        console.log(ticketDetailList.value, 'ticketDetailList')
        if (selectList.value?.length) {
            selectList.value.forEach(i => {
                const index = ticketDetailList.value.findIndex(k => k.id === i.id)
                if (index !== -1) {
                    const curSelect = ticketDetailList.value[index]
                    if (i.companyName === curSelect.companyName && i.type === curSelect.type && i.disableId !== curSelect.disableId) {
                        curSelect.disabled = true
                    } else {
                        curSelect.checked = true
                    }
                }
            })
        }
        totalMoney.value = 0
        let count = 0
        ticketDetailList.value.forEach(i => {
            if (i.checked) {
                count++
                totalMoney.value = Decimal.add(totalMoney.value, i.amount)
            }
        })
        if (ticketDetailList.value.length !== 0) {
            console.log(count, ticketDetailList.value.length, 'uyhfasuyhasfdyhusduyh')
            if (count === ticketDetailList.value.length) {
                checkAll.value = true
                isIndeterminate.value = false
            }
            if (count < ticketDetailList.value.length && count !== 0) {
                checkAll.value = false
                isIndeterminate.value = true
            }
            if (count < ticketDetailList.value.length && count === 0) {
                checkAll.value = false
                isIndeterminate.value = false
            }
        }
        if (ticketDetailList.value.length === 0) {
            checkAll.value = false
            isIndeterminate.value = false
        }
    })
}

const selectList = ref([])
const handleChange = (ev, item) => {
    if (ev) {
        item.uploadId = curItem.value.id
        item.invoiceUrl = curItem.value.invoiceUrl
        item.disableId = curItem.value.id
        item.type = curItem.value.type
        item.ticketMonth = curItem.value.month
        selectList.value.push(item)
        totalMoney.value = Decimal.add(totalMoney.value, item.amount)
    } else {
        const index = selectList.value.findIndex(i => i.id === item.id)
        if (index !== -1) {
            selectList.value.splice(index, 1)
            totalMoney.value = Decimal.sub(totalMoney.value, item.amount)
        }
    }
    if (selectList.value?.length === ticketDetailList.value.length && selectList.value.length !== 0) {
        checkAll.value = true
        isIndeterminate.value = false
    } else if (selectList.value.length === 0) {
        checkAll.value = false
        isIndeterminate.value = false
    } else {
        isIndeterminate.value = true
        checkAll.value = false
    }
}

const handleCancel = () => {
    emits('success')
    ticketList.value = []
    ticketDetailList.value = []
    selectList.value = []
    showDialog.value = false
}

const filterName = (type) => {
    const map = {
        0: '日日保',
        2: '电子签',
        3: '长期保'
    }
    return map[type]
}

const handleConfirm = () => {
    if (!selectList.value?.length) {
        ElMessage.error('请先选择要处理的发票')
        return
    }
    const params = []
    selectList.value.forEach(i => {
        const index = params.findIndex(k => k.uploadId === i.uploadId)
        if (index !== -1) {
            params[index].invoiceList.push({
                id: i.id,
                month: i.month,
                status: i.status,
            })
        } else {
            const data = {
                uploadId: i.uploadId,
                invoiceUrl: i.invoiceUrl,
                invoiceList: [{
                    id: i.id,
                    month: i.month,
                    status: i.status
                }]
            }
            params.push(data)
        }
    })
    syncInvoice(params).then(res => {
        handleCancel()
    })
}

const handlePreview = (item) => {
    showPreview.value = true
    previewUrl.value = item.invoiceUrl
}

const handleDateChange = () => {
    emits('update:month', selectMonth.value)
}

onMounted(() => {
})
watch(() => props.show, (newval) => {
    showDialog.value = newval
})
watch(showDialog, (newval) => {
    emits('update:show', newval)
})
watch(() => props.list, (newval) => {
    console.log(44444, newval)
    ticketList.value = newval
    if (newval?.length) {
        curItem.value = ticketList.value[0]
        handleClick(curItem.value)
    } else {
        curItem.value = ''
        ticketDetailList.value = []
        totalMoney.value = 0
    }
}, {
    deep: true
})

watch(() => props.month, (newval) => {
    selectMonth.value = newval
}, {
    immediate: true
})
</script>
<style lang="scss" scoped>
.left {
    width: 300px;
    flex-shrink: 0;

    .item {
        line-height: 32px;
        cursor: pointer;
        padding: 0 12px;
        border-left: 3px solid #fff;
    }

    .companyName {
        width: 200px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }

    .active {
        color: #0256ff;
        background: lighten(#0256ff, 40%);
        border-color: #0256ff;
    }
}

.center {
    flex: 1;
    padding-left: 20px;
    position: relative;

    .calc-box {
        position: sticky;
        right: 0;
        bottom: 0;
        text-align: right;
        background: #fff;
        padding-right: 20px;
    }
}

.right {
    // width: 300px;
    border: 1px solid #ccc;
    padding: 16px;
    border-radius: 10px;
    margin-left: 16px;
}

.left-box {
    border: 1px solid #ccc;
    padding: 16px;
    border-radius: 10px;
}

.select-item {
    line-height: 26px;
    border-bottom: 1px solid #eee;
    padding: 5px 0;
}

.limitHeight {
    max-height: 500px;
    overflow: auto;
}

.disabled {
    color: #ccc;
}
</style>
